package com.cntaiping.workutil.prometheus;

import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class StreamThread extends Thread{
    private static final Logger LOGGER = LoggerFactory.getLogger(StreamThread.class);

    public InputStream inputStream;

    boolean flag;

    public StreamThread(InputStream inputStream,boolean flag){
        this.inputStream = inputStream;
        this.flag = flag;
    }

    @SneakyThrows
    public void run(){
        BufferedReader bw = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
        try {
            StringBuilder buffer = new StringBuilder();
            String input;

            while ((input = bw.readLine()) != null) {
                buffer.append(input).append("\n");
            }
            if(StringUtils.isBlank(buffer)){
                return;
            }
            if(flag){
                LOGGER.info("正常执行结果:");
            }else {
                LOGGER.error("执行任务异常结果:");
            }
            System.out.println(buffer.toString());
        } catch (Exception e) {
            LOGGER.error("命令执行异常:{}", e.getMessage());
        } finally {
            try {
                bw.close();
            } catch (Exception e) {
                LOGGER.error("关闭异常:{}", e.getMessage());
            }

        }
    }

}
